package com.gx.telephonedemo2;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gx.telephonedemo2.activity.BaseActivity;
import com.gx.telephonedemo2.adapter.InterceptAdapter;
import com.gx.telephonedemo2.adapter.RecordAdapter;
import com.gx.telephonedemo2.fragment.PlaybackDialogFragment;
import com.gx.telephonedemo2.fragment.RecordAudioDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements RecordAdapter.PlayClickListener {

    private final String TAG = "MainActivity";

    String recordPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CallAutoRecord";
    MediaRecorder mMediaRecorder;
    private IntentFilter mNetIntentFilter = new IntentFilter();


    private ArrayList<Map<String, String>> mInterceptData = new ArrayList<>();
    private InterceptAdapter mInterceptAdapter;
    private PhoneStateReceiver mReceiver;

    private ArrayList<Map<String, String>> mRecordData = new ArrayList<>();
    private RecordAdapter mRecordAdapter;

    private ListView lvIntercept;
    private TextView tvIntercept;
    private TextView tvRecord;
    private ListView lvRecord;

    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        tvIntercept = findViewById(R.id.tvIntercept);
        tvRecord = findViewById(R.id.tvRecord);

        //初始化拦截列表
        lvIntercept = findViewById(R.id.lvIntercept);
        mInterceptAdapter = new InterceptAdapter(MainActivity.this, mInterceptData);
        lvIntercept.setAdapter(mInterceptAdapter);

        //初始化录音列表
        lvRecord = findViewById(R.id.lvRecord);
        mRecordAdapter = new RecordAdapter(MainActivity.this, mRecordData, this);
        lvRecord.setAdapter(mRecordAdapter);
//        lvRecord.setOnItemClickListener((adapterView, view, i, l) -> {
//            clickPlay(true, mRecordData.get(i).get("name"));
//        });

        //开始录音
        findViewById(R.id.main_btn_record_sound).setOnClickListener(view -> {
            final RecordAudioDialogFragment fragment = RecordAudioDialogFragment.newInstance();
            fragment.show(getSupportFragmentManager(), RecordAudioDialogFragment.class.getSimpleName());
            fragment.setOnCancelListener(fragment::dismiss);
        });

        //播放录音
        findViewById(R.id.main_btn_play_sound).setOnClickListener(view -> {
            RecordingItem recordingItem = new RecordingItem();
            SharedPreferences sharePreferences = getSharedPreferences("sp_name_audio", MODE_PRIVATE);
            final String filePath = sharePreferences.getString("audio_path", "");
            long elpased = sharePreferences.getLong("elpased", 0);
            recordingItem.setFilePath(filePath);
//            recordingItem.setLength((int) elpased);
            recordingItem.setLength(0);
            PlaybackDialogFragment fragmentPlay = PlaybackDialogFragment.newInstance(recordingItem);
            fragmentPlay.show(getSupportFragmentManager(), PlaybackDialogFragment.class.getSimpleName());
        });

        //拦截记录
        findViewById(R.id.tvIntercept).setOnClickListener(view -> {
            lvIntercept.setVisibility(View.VISIBLE);
            lvRecord.setVisibility(View.GONE);
            tvIntercept.setBackgroundColor(getResources().getColor(R.color.holo_green_dark));
            tvRecord.setBackgroundColor(getResources().getColor(R.color.darker_gray));
        });

        findViewById(R.id.tvRecord).setOnClickListener(view -> {
            //通话记录
            lvIntercept.setVisibility(View.GONE);
            lvRecord.setVisibility(View.VISIBLE);
            tvIntercept.setBackgroundColor(getResources().getColor(R.color.darker_gray));
            tvRecord.setBackgroundColor(getResources().getColor(R.color.holo_green_dark));
            mRecordData.clear();
            List<String> a = Utils.getFilesAllName(recordPath);
            if (a != null) {
                for (int i = 0; i < a.size(); i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", a.get(i));
                    mRecordData.add(map);
                }
            }
            mRecordAdapter.notifyDataSetChanged();
        });

        //更新通讯录列表
        findViewById(R.id.btnUpdata).setOnClickListener(view -> {
            loadMailList();
        });

        findViewById(R.id.fab).setOnClickListener(view -> {
            //拨号
            toCallPhoneUI("");
        });
        //注册电话拦截
        registerPhoneReceiver();
    }

    //更新通讯录列表
    private void loadMailList() {
        showLoadingDialog();
        Observable.create((ObservableOnSubscribe<String>) subscriber -> {
            Constant.blockCalls.clear();
            Constant.blockCalls.addAll(Utils.getPhoneNum(MainActivity.this));
            subscriber.onNext("hello");
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    hideLoadingDialog();
                    Toast.makeText(MainActivity.this, "更新完成！", Toast.LENGTH_SHORT).show();
                });
    }

    /**
     * 跳转至拨号界面
     */
    private void toCallPhoneUI(String phoneNumber) {
        //前往拨号页面拨打
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNumber);
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void clickPlay(String path) {
        RecordingItem recordingItem = new RecordingItem();
        recordingItem.setFilePath(path);
        recordingItem.setLength(0);
        PlaybackDialogFragment fragmentPlay = PlaybackDialogFragment.newInstance(recordingItem);
        fragmentPlay.show(getSupportFragmentManager(), PlaybackDialogFragment.class.getSimpleName());
    }

    private void registerPhoneReceiver() {
        mReceiver = new PhoneStateReceiver();
        mNetIntentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
        mNetIntentFilter.addAction("android.intent.action.PHONE_STATE");
        mNetIntentFilter.setPriority(Integer.MAX_VALUE);
        registerReceiver(mReceiver, mNetIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "activity onDestroy。。");
        unregisterReceiver(mReceiver);
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        Log.d(TAG, "更新拦截列表" + messageEvent.getMessage());
        notifiInterceptList(messageEvent.getMessage());
    }

    //更新拦截列表
    private void notifiInterceptList(String num) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());

        Map<String, String> map = new HashMap<>();
        map.put("num", num);
        map.put("time", formatter.format(curDate));
        mInterceptData.add(map);
        mInterceptAdapter.notifyDataSetChanged();
    }
}
